#!/usr/bin/env python3
"""
安装 Changelog 自动化系统
"""

import os
import shutil
from pathlib import Path
import subprocess
import stat


def setup_git_hooks():
    """设置 Git hooks"""
    git_hooks_dir = Path('.git/hooks')
    
    if not git_hooks_dir.exists():
        print("❌ 未找到 .git/hooks 目录，请确保在 git 仓库根目录运行")
        return False
    
    # 创建 post-commit hook
    post_commit_hook = git_hooks_dir / 'post-commit'
    
    hook_content = f"""#!/bin/bash
# Auto-update Unreleased section in CHANGELOG.md

cd "{Path.cwd()}"
python scripts/post_commit_hook.py
"""
    
    post_commit_hook.write_text(hook_content, encoding='utf-8')
    
    # 在 Windows 上不需要设置执行权限，但为了兼容性还是设置一下
    try:
        current_permissions = post_commit_hook.stat().st_mode
        post_commit_hook.chmod(current_permissions | stat.S_IEXEC)
    except:
        pass
    
    print("✅ Git post-commit hook 已安装")
    return True


def create_scripts_shortcuts():
    """创建便捷脚本"""
    
    # Windows 批处理脚本
    update_changelog_bat = Path('update_changelog.bat')
    update_changelog_bat.write_text("""@echo off
echo Updating Changelog...
python scripts\\update_changelog.py
pause
""", encoding='utf-8')
    
    # PowerShell 脚本
    update_changelog_ps1 = Path('update_changelog.ps1')
    update_changelog_ps1.write_text("""# Changelog Update Script
Write-Host "Updating Changelog..." -ForegroundColor Green
python scripts\\update_changelog.py
""", encoding='utf-8')
    
    print("✅ 快捷脚本已创建:")
    print("   - update_changelog.bat (批处理)")
    print("   - update_changelog.ps1 (PowerShell)")


def update_gitignore():
    """更新 .gitignore"""
    gitignore_path = Path('.gitignore')
    
    gitignore_entries = [
        "# Changelog automation",
        "__pycache__/",
        "*.pyc",
        "*.pyo",
    ]
    
    if gitignore_path.exists():
        content = gitignore_path.read_text()
        if "# Changelog automation" not in content:
            content += "\n" + "\n".join(gitignore_entries) + "\n"
            gitignore_path.write_text(content, encoding='utf-8')
            print("✅ .gitignore 已更新")
    else:
        gitignore_path.write_text("\n".join(gitignore_entries) + "\n", encoding='utf-8')
        print("✅ .gitignore 已创建")


def create_github_workflow():
    """创建 GitHub Actions 工作流"""
    workflow_dir = Path('.github/workflows')
    workflow_dir.mkdir(parents=True, exist_ok=True)
    
    workflow_content = """name: Auto Update Changelog

on:
  push:
    branches: [ main, master ]
  pull_request:
    branches: [ main, master ]

jobs:
  changelog:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v3
      with:
        fetch-depth: 0  # 获取完整历史
    
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.9'
    
    - name: Generate Changelog
      run: |
        python scripts/changelog_generator.py --dry-run
    
    - name: Validate Changelog Format
      run: |
        if [ -f "CHANGELOG.md" ]; then
          echo "✅ CHANGELOG.md exists"
          grep -q "## \\[Unreleased\\]" CHANGELOG.md && echo "✅ Unreleased section found"
          grep -q "Keep a Changelog" CHANGELOG.md && echo "✅ Format reference found"
        else
          echo "❌ CHANGELOG.md not found"
          exit 1
        fi
"""
    
    workflow_file = workflow_dir / 'changelog.yml'
    workflow_file.write_text(workflow_content, encoding='utf-8')
    print("✅ GitHub Actions 工作流已创建")


def main():
    """主函数"""
    print("🔧 安装 Changelog 自动化系统...")
    
    # 检查是否在 git 仓库中
    if not Path('.git').exists():
        print("❌ 当前目录不是 git 仓库")
        return
    
    # 创建 scripts 目录（如果不存在）
    scripts_dir = Path('scripts')
    scripts_dir.mkdir(exist_ok=True)
    
    # 设置各个组件
    setup_git_hooks()
    create_scripts_shortcuts()
    update_gitignore()
    create_github_workflow()
    
    print("\n🎉 Changelog 自动化系统安装完成!")
    print("\n📖 使用方法:")
    print("1. 自动模式: Git hooks 会在每次提交后自动更新 Unreleased 部分")
    print("2. 手动更新: 运行 `python scripts/update_changelog.py` 或 `update_changelog.bat`")
    print("3. 生成版本: 运行 `python scripts/changelog_generator.py --version-type patch`")
    print("\n💡 建议:")
    print("- 使用 Conventional Commits 格式: feat: 新功能, fix: 修复, docs: 文档")
    print("- 定期运行手动更新来整理和发布新版本")
    print("- 在发布前检查 CHANGELOG.md 内容")


if __name__ == '__main__':
    main()